import string
from datetime import datetime
import random

from rest_framework import serializers
from rest_framework.fields import CurrentUserDefault

from app.goods.models import Goods
from app.goods.serializers import GoodListSerializer
from app.trade.models import ShoppingCart, OrderInfo, OrderGoods


class ShoppingCartSerializer(serializers.Serializer):
    user = serializers.HiddenField(default=CurrentUserDefault())
    goods = serializers.PrimaryKeyRelatedField(queryset=Goods.objects.all(), required=True)
    nums = serializers.IntegerField(required=True, error_messages={
        'required': '必须填写数量'
    })

    def create(self, validated_data):
        goods = validated_data['goods']
        user = validated_data['user']
        nums = validated_data['nums']
        query_goods = ShoppingCart.objects.filter(user=user, goods=goods).first()
        print(query_goods)
        if query_goods:
            # 如果该商品已经加入购物车，则更新其数量
            query_goods.nums += nums
            query_goods.save()
            return query_goods
        else:
            # 如果不存在，则实例化对象添加
            instance = ShoppingCart(user=user, goods=goods, nums=nums)
            instance.save()
            return instance

    def update(self, instance, validated_data):
        instance.nums = validated_data['nums']
        instance.save()
        return instance


# 购物车详情的序列化
# class GoodsSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = Goods
#         fields = '__all__'


class ShoppingCartDetailSerializer(serializers.ModelSerializer):
    goods = GoodListSerializer()

    class Meta:
        model = ShoppingCart
        fields = '__all__'


# 订单信息序列化
class OrderInfoSerializer(serializers.ModelSerializer):
    # 有一些字段时不需要填写的
    user = serializers.HiddenField(default=CurrentUserDefault())
    order_sn = serializers.CharField(read_only=True)
    pay_status = serializers.CharField(read_only=True)
    pay_time = serializers.DateTimeField(read_only=True, default=datetime.now)
    order_mount = serializers.FloatField(read_only=True)
    nonce_str = serializers.CharField(read_only=True)
    trade_no = serializers.CharField(read_only=True)
    add_time = serializers.DateTimeField(read_only=True)

    # 生成订单号
    def generate_order_sn(self):
        code = ''.join(random.sample(string.digits, 4))
        return datetime.now().strftime('%y%m%d%H%M%S') + str(self.context['request'].user.id) + code

    def validate(self, attrs):
        attrs['order_sn'] = self.generate_order_sn()
        return attrs

    class Meta:
        model = OrderInfo
        fields = '__all__'


class OrderGoodsSerializer(serializers.ModelSerializer):
    goods = GoodListSerializer()

    class Meta:
        model = OrderGoods
        fields = '__all__'


class orderInfoDetailSerializer(serializers.ModelSerializer):
    goods = OrderGoodsSerializer(many=True)

    class Meta:
        model = OrderInfo
        fields = '__all__'
